//
//  ChatViewController.m
//  BaiYing_Thinker
//
//  Created by 鹏 朱 on 15/10/26.
//  Copyright (c) 2015年 XKJH. All rights reserved.
//

#import "ChatViewController.h"
#import "SessonContentMessage.h"
#import "AppDelegate.h"
#import "DatabaseCache.h"
#import "SubjectMessage.h"
#import "SessionMessage.h"
#import "XKO_CreateUIViewHelper.h"
#import "NSString+Teshuzifu.h"
#import "FileMangeHelper.h"
#import "UploadFile.h"
#import "PlayerHelper.h"
#import "VoiceView.h"
#import "ChatViewCell.h"
#import "ChatViewCellFrame.h"
#import "ICarouselView.h"
#import "HiddenChatTableView.h"
#import "MainChatController.h"
#import "PopPluginTableView.h"

#define      KTableViewHeight       kScreenHeight - 70
#define      KScrollViewTop         0

@interface ChatViewController()
{
    IFlySpeechSynthesizer * _iFlySpeechSynthesizer;
}

@property(nonatomic, strong) SessonContentMessage *subjectMessage;
@property(nonatomic, strong) SessonContentMessage *firstMessage;
@property(nonatomic, strong) UILabel *headText;
@property(nonatomic, strong) HiddenChatTableView *bottomTouchView;
@property(nonatomic, strong) HiddenChatTableView *topTouchView;
@property(nonatomic, strong) UIImageView *welcomeView;
@property(nonatomic, strong) UIView *headerView;
@property(nonatomic, strong) UIView *footerView;
@property(nonatomic, strong) UIView *redView;
@property(nonatomic, strong) VoiceView *voiceView;
@property(nonatomic, strong) PopPluginTableView *subjectPluginTableView;
@property(nonatomic, strong) PopPluginTableView *sessionPluginTableView;
@property(nonatomic, strong) UIButton *sessionMarkBtn;
@property(nonatomic, strong) UIButton *subjectMarkBtn;
@property(nonatomic, strong) NSMutableDictionary *contentIdList;

@end

@implementation ChatViewController

- (id)initWithFrame:(CGRect)frame dataSource:(NSMutableArray *)dataSource previousDataList:(NSMutableArray *)previousDataList nextDataList:(NSMutableArray *)nextDataList {
    
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = kGetColor(18, 38, 74);

        UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, KScrollViewTop, kScreenWidth, 20)];
        topView.backgroundColor = kGetColor(18, 38, 74);
        [self addSubview:topView];
        
        [self addSubview:self.tableView];
        [self addSubview:self.chatBottomView];

        [self createiFlySpeechSynthesizer];
        
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.dataListOne = dataSource;
        self.tableView.backgroundColor = kGetColor(18, 38, 74);
        self.contentIdList = [[NSMutableDictionary alloc] init];
        
        [self reloadData];
        
        self.previousDataList = previousDataList;
        self.nextDataList = nextDataList;
        [self.tableView addSubview:self.bottomTouchView];
        [self.tableView addSubview:self.topTouchView];

    }
    
    return self;
}

#pragma mark - getter

- (TouchTableView *)tableView {
    
    if (!_tableView) {
        TouchTableView *tableView = [[TouchTableView alloc] initWithFrame:CGRectMake(0, 20 + KScrollViewTop, kScreenWidth, KTableViewHeight) style:UITableViewStylePlain];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.touchDelegate = self;
        tableView.delaysContentTouches = NO;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [tableView setSeparatorInset:UIEdgeInsetsZero];
        tableView.contentOffset = CGPointMake(0, 0);
        tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
        _tableView = tableView;
    }
    
    return _tableView;
}

- (ChatBottomView *)chatBottomView {
    if (!_chatBottomView) {
        
        _chatBottomView = [[ChatBottomView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 50, kScreenWidth, 50) sendMessageBlock:^(NSString *messageText, UploadFileType sendType) {
            
            if (!IsEmpty(messageText)) {
                [self sendMessageWithMessageText:messageText uploadType:sendType fileUrl:nil localFileName:nil imageSize:CGSizeZero];
            }
            
        } recordFinishBlock:^(NSTimeInterval time) {
            
            [self recordFinishWithTime:time];
            
        } sartIFlySpeechBlock:^(NSString *messageText, UploadFileType sendType, NSString *fileUrl, NSString *localFileName, CGSize imageSize){
            
            [self sendMessageWithMessageText:messageText uploadType:sendType fileUrl:fileUrl localFileName:localFileName imageSize:imageSize];

        } addPictureBlock:^(UIImage *selectedImg){
            
        }];
        _chatBottomView.backgroundColor = [UIColor clearColor];
    }
    
    return _chatBottomView;
}

- (VoiceView *)voiceView {
    
    if (_voiceView) {
        _voiceView = [[VoiceView alloc] initWithFrame:CGRectMake(0, 0, 30, 30) type:VoiceViewTypeOthers];
    }
    return _voiceView;
}

- (UIView *)footerView {
    
    if (!_footerView) {
        
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 120)];
        header.backgroundColor = kGetColor(18, 38, 74);
        
        UILabel *headText = [XKO_CreateUIViewHelper createLabelWithFont:[UIFont boldSystemFontOfSize:33] fontColor:[UIColor whiteColor] text:self.subjectMessage.msg_content];
        headText.numberOfLines = 0;
        headText.text = self.subjectMessage.msg_content;
        headText.textAlignment = NSTextAlignmentCenter;
        [header addSubview:headText];
        
        [headText mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(header.mas_centerX);
            make.centerY.equalTo(header.mas_centerY);
            make.width.equalTo(@(280));
        }];
        _footerView = header;
    }
    
    return _footerView;
}

- (UIView *)headerView {
    
    if (!_headerView) {
        
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        header.backgroundColor = kGetColor(18, 38, 74);
        
        UILabel *headText = [XKO_CreateUIViewHelper createLabelWithFont:[UIFont boldSystemFontOfSize:18] fontColor:[UIColor whiteColor] text:self.subjectMessage.msg_content];
        headText.numberOfLines = 1;
        headText.text = self.firstMessage.subject_content;
        headText.textAlignment = NSTextAlignmentLeft;
        _headText = headText;
        [header addSubview:headText];
        
        [headText mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(header.mas_centerX);
            make.centerY.equalTo(header.mas_centerY);
            make.width.equalTo(@(280));
        }];
        
        [header addSubview:self.sessionMarkBtn];
        [self.sessionMarkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(header.mas_centerX).offset(kScreenWidth/2 - 60);
            make.centerY.equalTo(header.mas_centerY);
            make.width.equalTo(@(32));
        }];
        
        [header addSubview:self.subjectMarkBtn];
        [self.subjectMarkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(header.mas_centerX).offset(kScreenWidth/2 - 20);
            make.centerY.equalTo(header.mas_centerY);
            make.width.equalTo(@(32));
        }];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10, 49, kScreenWidth-20 , 1)];
        lineView.backgroundColor = [UIColor whiteColor];
        [header addSubview:lineView];
        
        _headerView = header;
    }
    
    return _headerView;
}

- (HiddenChatTableView *)bottomTouchView {
    
    if (!_bottomTouchView) {
        
        _bottomTouchView = [[HiddenChatTableView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 50, kScreenWidth, kScreenHeight - 70) dataSource:self.nextDataList];
        _bottomTouchView.hidden = YES;
    }
    
    return _bottomTouchView;
}

- (HiddenChatTableView *)topTouchView {
    
    if (!_topTouchView) {
        
        _topTouchView = [[HiddenChatTableView alloc] initWithFrame:CGRectMake(0, -(kScreenHeight - 70), kScreenWidth, kScreenHeight - 70) dataSource:self.previousDataList];
        _topTouchView.hidden = YES;
        
    }
    
    return _topTouchView;
}

- (UIButton *)sessionMarkBtn {
    
    if (!_sessionMarkBtn) {
        
        _sessionMarkBtn = [XKO_CreateUIViewHelper createUIButtonWithNormalImage:IMAGE(@"Keyboard") highlightedImage:nil radiusSize:0 frame:CGRectZero];
        [_sessionMarkBtn addTarget:self action:@selector(sessionMarkBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _sessionMarkBtn;
}

- (UIButton *)subjectMarkBtn {
    
    if (!_subjectMarkBtn) {
        
        _subjectMarkBtn = [XKO_CreateUIViewHelper createUIButtonWithNormalImage:IMAGE(@"Keyboard") highlightedImage:nil radiusSize:0 frame:CGRectZero];
        [_subjectMarkBtn addTarget:self action:@selector(subjectMarkBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _subjectMarkBtn;
}

- (PopPluginTableView *)subjectPluginTableView {
    
    if (!_subjectPluginTableView) {
        _subjectPluginTableView = [[PopPluginTableView alloc] initWithFrame:CGRectMake(0, self.tableView.frame.size.height, self.tableView.frame.size.width, self.tableView.frame.size.height - 54) type:SubjectDataModelType didSelectedBlock:^{
            [self subjectPluginTableViewDidSelected];
        }];
    }
    
    return _subjectPluginTableView;
}

- (PopPluginTableView *)sessionPluginTableView {
    
    if (!_sessionPluginTableView) {
        _sessionPluginTableView = [[PopPluginTableView alloc] initWithFrame:CGRectMake(-self.tableView.frame.size.width, 54, self.tableView.frame.size.width, self.tableView.frame.size.height - 54) type:SessionDataModelType didSelectedBlock:^{
            [self sessionPluginTableViewDidSelected];
        }];
    }
    
    return _sessionPluginTableView;
}

- (UIImageView *)welcomeView {
    
    if (_welcomeView) {
        
        CGFloat y_point = self.tableView.contentSize.height;
        if (y_point < kScreenHeight) {
            y_point = kScreenHeight;
        }
        
        _welcomeView = [[UIImageView alloc] initWithFrame:CGRectMake(0, y_point, kScreenWidth, kScreenHeight)];
    }
    
    return _welcomeView;
}

#pragma mark - setter

- (void)setPreviousDataList:(NSMutableArray *)previousDataList {
    
    if (_previousDataList != previousDataList) {
        
        _previousDataList = previousDataList;
        
        self.topTouchView.dataListOne = _previousDataList;
        [self.topTouchView reloadData];
    }
}

- (void)setNextDataList:(NSMutableArray *)nextDataList {
    
    if (_nextDataList != nextDataList) {
        
        _nextDataList = nextDataList;
        
        self.bottomTouchView.dataListOne = _nextDataList;
        [self.bottomTouchView reloadData];
        
    }
}

#pragma mark - private methord
         
- (void)addTapGestureRecognizer{
 
     UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
     singleTap.delaysTouchesBegan = YES;
     singleTap.numberOfTapsRequired = 1;
     [self.tableView addGestureRecognizer:singleTap];
}

- (void)getFirstSubject {
    
    
}
                                   
- (void)subjectPluginTableViewDidSelected {
   
    [self subjectMarkBtnClicked:nil];
}
                                   
- (void)sessionPluginTableViewDidSelected {
   
   [self sessionMarkBtnClicked:nil];
}

- (void)subjectMarkBtnClicked:(UIButton *)sender {
    
    if (self.subjectPluginTableView.superview) {
        
        [self.subjectPluginTableView setFrame:CGRectMake(0, 54, self.tableView.frame.size.width, self.tableView.frame.size.height - 54)];
        [UIView animateWithDuration:0.35 animations:^{
            
            [self.subjectPluginTableView setFrame:CGRectMake(0, self.tableView.frame.size.height, self.tableView.frame.size.width, self.tableView.frame.size.height - 54)];
            
        } completion:^(BOOL finished) {
            
            [self.subjectPluginTableView removeFromSuperview];
        }];
        
    } else if(!self.sessionPluginTableView.superview) {
        [self.tableView addSubview:self.subjectPluginTableView];
        [self.subjectPluginTableView setFrame:CGRectMake(0, self.tableView.frame.size.height, self.tableView.frame.size.width, self.tableView.frame.size.height - 54)];
        [UIView animateWithDuration:0.35 animations:^{
            
            [self.subjectPluginTableView setFrame:CGRectMake(0, 54, self.tableView.frame.size.width, self.tableView.frame.size.height - 54)];
            
        } completion:^(BOOL finished) {
            
            
        }];
    }
}

- (void)sessionMarkBtnClicked:(UIButton *)sender {
    
    if (self.sessionPluginTableView.superview) {
        
        [self.sessionPluginTableView setFrame:CGRectMake(0, 54, self.tableView.frame.size.width, self.tableView.frame.size.height - 54)];
        [UIView animateWithDuration:0.35 animations:^{
            
            [self.sessionPluginTableView setFrame:CGRectMake(-self.tableView.frame.size.width, 54, self.tableView.frame.size.width, self.tableView.frame.size.height - 54)];
            
        } completion:^(BOOL finished) {
            
            [self.sessionPluginTableView removeFromSuperview];
        }];
        
    } else if(!self.subjectPluginTableView.superview){
        [self.tableView addSubview:self.sessionPluginTableView];
        [self.sessionPluginTableView setFrame:CGRectMake(-self.tableView.frame.size.width, 54, self.tableView.frame.size.width, self.tableView.frame.size.height - 54)];
        [UIView animateWithDuration:0.35 animations:^{
            
            [self.sessionPluginTableView setFrame:CGRectMake(0, 54, self.tableView.frame.size.width, self.tableView.frame.size.height - 54)];
            
        } completion:^(BOOL finished) {
            
            
        }];
    }
}


- (void)reloadData {
    
    if (!self.dataListOne || self.dataListOne.count == 0) {
        
        //开启新的话题
        NSDictionary *dic = @{@"clientid":@"BAIYING_WORKER01_CLIENT",@"content":@{@"sys_code":@"9999",@"text":@"请问有什么可以帮您的？",@"type":@"TEXT"},@"model":@"SYSTEM",@"msg_id":kAppDelegate.messageId};
        SessonContentMessage *message = [[SessonContentMessage alloc] initWithDictionary:dic isMyself:@1];
        self.subjectMessage = message;
        self.tableView.tableFooterView = [self footerView];
        self.firstMessage = nil;
        
    } else if (self.dataListOne.count == 1) {
        
        SessonContentMessage *subject = [self.dataListOne objectAtIndex:0];
        if ([subject.sys_code isEqualToString:@"9999"] || [subject.sys_code isEqualToString:@"1005"]) {
            
            self.subjectMessage = subject;
            [self.dataListOne removeObject:subject];
            self.tableView.tableFooterView = [self footerView];
            self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
            
        } else {
            
            self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        }
        
        self.firstMessage = subject;
        
    } else {
        
        self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        SessonContentMessage *subject = [self.dataListOne objectAtIndex:0];
        self.firstMessage = subject;
        
    }
    
    if (self.firstMessage && !IsEmpty(self.firstMessage.subject_content)) {

        self.tableView.tableHeaderView = [self headerView];
        _headText.text = self.firstMessage.subject_content;
        
    } else {
        
        self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];

    }
    
    [self.tableView reloadData];
    [self reloadBottomTouchViewData];
    [self reloadTopTouchViewData];
    
}


- (void)reloadBottomTouchViewData {
    
    self.bottomTouchView.dataListOne =  self.nextDataList;
    [self.bottomTouchView reloadData];
    
}

- (void)reloadTopTouchViewData {
    
    self.topTouchView.dataListOne =  self.previousDataList;
    [self.topTouchView reloadData];
    
}

- (void)handleSingleTap:(UITouch *)touch {
    
    [self.chatBottomView.inputTextField resignFirstResponder];
}


- (void)resetBottomTouchFrame {
    
    CGFloat y_point = self.tableView.contentSize.height;
    if (y_point < kScreenHeight - 50) {
        y_point = kScreenHeight - 50;
    } else {
        y_point += 100;
    }
    
    CGRect frame = self.bottomTouchView.frame;
    frame.origin.y = y_point;
    if (frame.size.height < kScreenHeight - 70) {
        frame.size.height = kScreenHeight - 70;
    }
    self.bottomTouchView.frame = frame;
    
}

- (void)resetTopTouchViewFrame {
    
    CGRect frame = self.topTouchView.frame;
    frame.origin.y = -frame.size.height;
    self.topTouchView.frame = frame;
    
}

- (NSDictionary *)reBuildNewDictionary:(NSDictionary *)preDictionary uploadType:(UploadFileType)uploadType fileUrl:(NSString *)fileUrl imageSize:(CGSize)imageSize{
    
    NSString *typeString = @"";
    if (uploadType == UploadFileImageType) {
        typeString = @"IMAGE";
    } else if (uploadType == UploadFileAudioType) {
        typeString = @"AUDIO";
    } else if (uploadType == UploadFileVideoType) {
        typeString = @"VIDEO";
    }
    
    NSMutableDictionary *newDictionary = [[NSMutableDictionary alloc] init];
    [preDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        
        if ([key isEqualToString:@"content"] && obj) {
            
            NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc] init];
            [obj enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                [contentDictionary setObject:obj forKey:key];
            }];
            
            if (!IsEmpty(fileUrl)) {
                [contentDictionary setObject:typeString forKey:@"type"];
                [contentDictionary setObject:fileUrl forKey:@"url"];
            }
            
            if (uploadType == UploadFileImageType) {
                [contentDictionary setObject:[NSNumber numberWithFloat:imageSize.width] forKey:@"width"];
                [contentDictionary setObject:[NSNumber numberWithFloat:imageSize.height] forKey:@"height"];
            }
            
            [newDictionary setObject:contentDictionary forKey:key];

        } else {
            [newDictionary setObject:obj forKey:key];
        }
    }];
    
    return newDictionary;
}


- (void)sendMessageWithMessageText:(NSString *)messageText uploadType:(UploadFileType)uploadType fileUrl:(NSString *)fileUrl localFileName:(NSString *)localFileName imageSize:(CGSize)imageSize{
    
    NSString *subjectId;
    NSString *sessionId;
    NSDictionary *msgDict;
    
    NSString *contentType = (uploadType == AudioNormalType)?@"TEXT":(uploadType == UploadFileZipType)?@"COMPONENT":(uploadType == UploadFileImageType)?@"IMAGE":(uploadType == UploadFileAudioType)?@"AUDIO":(uploadType == UploadFileVideoType)?@"VIDEO":@"TEXT";
    
    if (self.firstMessage) {

        subjectId = self.firstMessage.subject_id;
        sessionId = self.firstMessage.session_id;
        self.firstMessage.sys_code = self.firstMessage.sys_code?self.firstMessage.sys_code:@"";
        
        if ([self.firstMessage.isMyself isEqual:@0]) {
            
            if ([self.firstMessage.model isEqualToString:@"SYSTEM"]) {
                
                /*
                    1000:绑定手机号
                    1001:输入验证码
                    1004:成功了
                    1005:开始百应之旅
                    1006:上传deviceToken
                 */
                
                if ([self.firstMessage.sys_code isEqualToString:@"1000"]) {
                    
                    msgDict = @{@"clientid":kAppDelegate.currentUser,@"content":@{@"sys_code":self.firstMessage.sys_code,@"text":messageText,@"type":contentType},@"model":@"SYSTEM",@"msg_id":subjectId};

                    
                } else if ([self.firstMessage.sys_code isEqualToString:@"1001"]) {
                    
                    msgDict = @{@"clientid":kAppDelegate.currentUser,@"content":@{@"sys_code":self.firstMessage.sys_code,@"text":messageText,@"type":contentType},@"model":@"SYSTEM",@"msg_id":subjectId};
                    
                } else if ([self.firstMessage.sys_code isEqualToString:@"1002"]) {
                    
                    
                } else if ([self.firstMessage.sys_code isEqualToString:@"1003"]) {
                    
                    
                } else if ([self.firstMessage.sys_code isEqualToString:@"1004"]) {
                    
                    msgDict = @{@"clientid":kAppDelegate.currentUser,@"content":@{@"sys_code":self.firstMessage.sys_code,@"text":messageText,@"type":contentType},@"model":@"TALK",@"msg_id":subjectId};
                    
                } else if ([self.firstMessage.sys_code isEqualToString:@"1005"]) {
                    
                    msgDict = @{@"clientid":kAppDelegate.currentUser,@"content":@{@"sys_code":self.firstMessage.sys_code,@"text":messageText,@"type":contentType},@"model":@"TALK",@"msg_id":subjectId};
                    
                } else if ([self.firstMessage.sys_code isEqualToString:@"1006"]) {
                    
                    msgDict = @{@"clientid":kAppDelegate.currentUser,@"content":@{@"sys_code":self.firstMessage.sys_code,@"text":kAppDelegate.deviceToken,@"type":contentType},@"model":@"SYSTEM",@"msg_id":subjectId};
                    
                } else {
                    
                    msgDict = @{@"clientid":kAppDelegate.currentUser,@"content":@{@"sys_code":self.firstMessage.sys_code,@"text":messageText,@"type":contentType},@"model":@"SYSTEM",@"msg_id":subjectId};
                    
                }
                
            } else if(IsEmpty(self.firstMessage.recevier)){
                
                if ([self.firstMessage.model isEqualToString:@"ASK"]) {
                    
                    // 回答人
                    msgDict = @{@"clientid":kAppDelegate.currentUser,@"content":@{@"sys_code":self.firstMessage.sys_code,@"text":messageText,@"type":contentType},@"model":@"TALK",@"msg_id":subjectId,@"toclientid":self.firstMessage.sender};

                } else {
                    // 收到机器人的响应
                    msgDict = @{@"clientid":kAppDelegate.currentUser,@"content":@{@"sys_code":self.firstMessage.sys_code,@"text":messageText,@"type":contentType},@"model":@"TALK",@"msg_id":subjectId};
                }
                
            } else {
                
                //收到别人的响应
                NSString *messageModel = [self.firstMessage.model isEqualToString:@"TALK"]?@"TALK":([self.firstMessage.model isEqualToString:@"ANSWER"]?@"TALK":([self.firstMessage.model isEqualToString:@"ASK"]?@"ANSWER":([self.firstMessage.model isEqualToString:@"SYSTEM"]?@"SYSTEM":@"TALK")));
                
                msgDict = @{@"clientid":kAppDelegate.currentUser,@"model":messageModel,@"msg_id":subjectId,@"to_range":@{@"rel":@"RANDOM",@"lbskm":@10},@"content":@{@"type":contentType,@"text":messageText,@"source":@"百应机器人"},@"toclientid":self.firstMessage.sender};

            }
            
        } else {
            
            if (self.dataListOne.count > 1) {
                
                SessonContentMessage *responseMessage;
                for (SessonContentMessage *subMessage in self.dataListOne) {

                    if ([subMessage.isMyself isEqual:@0]) {
                        
                        responseMessage = subMessage;
                        break;
                    }
                }
                
                
                //自己发的消息得到机器人的响应，和机器人聊天（否则没有响应，重新发送）。
                if (responseMessage) {
                    
                    msgDict = @{@"clientid":kAppDelegate.currentUser,@"model":@"TALK",@"msg_id":subjectId,@"to_range":@{@"rel":@"RANDOM",@"lbskm":@10},@"content":@{@"type":contentType,@"text":messageText,@"source":@"百应机器人"}};
                    
                } else {
                    
                    msgDict = @{@"clientid":kAppDelegate.currentUser,@"model":@"TALK",@"msg_id":subjectId,@"to_range":@{@"rel":@"RANDOM",@"lbskm":@10},@"content":@{@"type":contentType,@"text":messageText}};
                }
                
            } else {
                
                //自己发的消息没有得到响应,重新发送
                msgDict = @{@"clientid":kAppDelegate.currentUser,@"model":@"ASK",@"msg_id":subjectId,@"to_range":@{@"rel":@"RANDOM",@"lbskm":@10},@"content":@{@"type":contentType,@"text":messageText}};

            }
        }
        
    } else {
        
        subjectId = kAppDelegate.messageId;
        sessionId = kLocalSessionId;
        
        NSLog(@"%@",kAppDelegate.messageId);
        msgDict = @{@"clientid":kAppDelegate.currentUser,@"model":@"ASK",@"msg_id":kAppDelegate.messageId,@"to_range":@{@"rel":@"RANDOM",@"lbskm":@10},@"content":@{@"type":contentType,@"text":messageText}};

    }
    
    if (msgDict && msgDict.count > 0) {
        
        if (uploadType == AudioNormalType){
            
            SessonContentMessage *message = [[SessonContentMessage alloc] initWithDictionary:msgDict isMyself:@1];
            message.session_id = sessionId;
            
            [self refreshTableView:message];
            [self addLocalCachMessage:message];
            [kAppDelegate sendMessage:msgDict];
            
        } else {
            
            if (!IsEmpty(fileUrl) || uploadType == UploadFileImageType) {
                msgDict = [self reBuildNewDictionary:msgDict uploadType:uploadType fileUrl:fileUrl imageSize:imageSize];
            }
            SessonContentMessage *message = [[SessonContentMessage alloc] initWithDictionary:msgDict isMyself:@1];
            message.session_id = sessionId;
            message.local_Path = localFileName;
            
            if (IsEmpty(fileUrl)) {
                
                [self refreshTableView:message];
                [self addLocalCachMessage:message];
                
            } else {
                
                [self addLocalCachMessage:message];
                [kAppDelegate sendMessage:msgDict];
                
            }
            
        }
    }
}

- (void)addLocalCachMessage:(SessonContentMessage *)message {
    
    [[DatabaseCache shareInstance] addSessionContentInfo:message];

    if ([message.isMyself isEqual:@1] && [message.model isEqualToString:@"ASK"]) {
        
//        SubjectMessage *subjectMessage = [[SubjectMessage alloc] initWithSessonContentMessage:message];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"subject_id == %@",message.subject_id];
        NSArray *filteredSubject = [Util findObjectFromArrary:kAppDelegate.subjectList predicate:predicate];
        if (!filteredSubject) {
//            [kAppDelegate.subjectList addObject:subjectMessage];
            [kAppDelegate.rootVC reloadData];
        }
    }
}

- (void)refreshTableView:(SessonContentMessage *)message {
    
    [self.dataListOne addObject:message];
    [self reloadData];
    
    [self resetBottomTouchFrame];
    [self scrollToBottom];
}

- (void)scrollToBottom {
    
    if (self.dataListOne.count > 0) {
        
        CGFloat contentOffset = self.tableView.contentSize.height - self.tableView.frame.size.height;
        if (contentOffset <= 0) {
            contentOffset = 0;
        }
        [self.tableView setContentOffset:CGPointMake(0, contentOffset) animated:YES];

    }
}

//结束录音，转成MP3，发送给好友
- (void)recordFinishWithTime:(NSTimeInterval)time
{

}

//在线语音合成
- (void)createiFlySpeechSynthesizer {
    
    //1.创建合成对象
    _iFlySpeechSynthesizer = [IFlySpeechSynthesizer sharedInstance];
    _iFlySpeechSynthesizer.delegate = self;
    
    //2.设置合成参数
    //设置在线工作方式
    [_iFlySpeechSynthesizer setParameter:[IFlySpeechConstant TYPE_CLOUD]
                                  forKey:[IFlySpeechConstant ENGINE_TYPE]];
    //音量,取值范围 0~100
    [_iFlySpeechSynthesizer setParameter:@"50" forKey: [IFlySpeechConstant VOLUME]];
    
    //发音人,默认为”xiaoyan”,可以设置的参数列表可参考“合成发音人列表”
    [_iFlySpeechSynthesizer setParameter:@" xiaoyan " forKey: [IFlySpeechConstant VOICE_NAME]];
    
    //保存合成文件名,如不再需要,设置设置为nil或者为空表示取消,默认目录位于 library/cache下
    [_iFlySpeechSynthesizer setParameter:@"luyin2.pcm" forKey: [IFlySpeechConstant TTS_AUDIO_PATH]];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataListOne count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SessonContentMessage *subject = [self.dataListOne objectAtIndex:indexPath.row];
    DataModelType type = [subject.msg_type isEqualToString:@"TEXT"]?TextDataModelType:[subject.msg_type isEqualToString:@"COMPONENT"]?WebDataModelType:[subject.msg_type isEqualToString:@"IMAGE"]?ImageDataModelType:[subject.msg_type isEqualToString:@"AUDIO"]?AudioDataModelType:[subject.msg_type isEqualToString:@"VIDEO"]?VideoDataModelType:TextAndImageDataModelType;
        
    CGSize webSize = CGSizeMake(kScreenWidth - 40, 0);
    
    if (type == ImageDataModelType) {
        webSize.width = [subject.content_width floatValue];
        webSize.height = [subject.content_height floatValue];
        
    } 

    if ((type == WebDataModelType || type == ImageDataModelType) && self.contentIdList[subject.session_content_id]) {
        
        webSize = CGSizeFromString(self.contentIdList[subject.session_content_id]);
    }

    static NSString *cellId;
    if (type == TextDataModelType) {
        cellId = @"TextDataModelTypeIdentifier";
    } else if (type == WebDataModelType) {
        cellId = @"WebDataModelTypeIdentifier";
    } else if (type == ImageDataModelType) {
        cellId = @"ImageDataModelTypeIdentifier";
    } else if (type == VideoDataModelType) {
        cellId = @"VideoDataModelTypeIdentifier";
    } else if (type == AudioDataModelType) {
        cellId = @"AudioDataModelTypeIdentifier";
    } else if (type == TextAndImageDataModelType) {
        cellId = @"TextAndImageDataModelTypeIdentifier";
    } else {
        cellId = @"TextDataModelTypeIdentifier";
    }
    
    ChatViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (!cell) {
        cell = [[ChatViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId dataModelType:type webSize:webSize];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    } else {
        cell.dataModelType = type;
        cell.webSize = webSize;
    }
    
    WEAK_SELF
    cell.webFinishLoadBlock = ^(NSString *sizeString, NSNumber *contentId){
        
        if (contentId) {
            [weak_self.contentIdList setObject:sizeString forKey:contentId];
            
            //        [weak_self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            [weak_self.tableView reloadData];
        }
    };
    cell.pictureDidSelectedBlock = ^(NSString *speakString){
        [_iFlySpeechSynthesizer startSpeaking:speakString];
    };
    
    cell.message = subject;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SessonContentMessage *subject = [self.dataListOne objectAtIndex:indexPath.row];
    DataModelType type = [subject.msg_type isEqualToString:@"TEXT"]?TextDataModelType:[subject.msg_type isEqualToString:@"COMPONENT"]?WebDataModelType:[subject.msg_type isEqualToString:@"IMAGE"]?ImageDataModelType:[subject.msg_type isEqualToString:@"AUDIO"]?AudioDataModelType:[subject.msg_type isEqualToString:@"VIDEO"]?VideoDataModelType:TextAndImageDataModelType;
    
    CGSize webSize = CGSizeMake(kScreenWidth - 40, 0);
    
    if (type == ImageDataModelType) {
        webSize.width = [subject.content_width floatValue];
        webSize.height = [subject.content_height floatValue];
    }
    if ((type == WebDataModelType || type == ImageDataModelType) && self.contentIdList[subject.session_content_id]) {
        webSize = CGSizeFromString(self.contentIdList[subject.session_content_id]);
    }
    
    ChatViewCellFrame *frame = [[ChatViewCellFrame alloc] initWithDataModel:subject dataModelType:type webSize:webSize];
    return frame.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

//    SessonContentMessage *subject = [self.dataListOne objectAtIndex:indexPath.row];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat height = scrollView.contentSize.height-scrollView.frame.size.height;
    if (height<0) {
        height = 0;
    }
    if (scrollView.contentOffset.y > height) {
        
        if (self.bottomTouchView.hidden == YES  && ![NSStringFromCGRect(self.bottomTouchView.frame) isEqualToString:NSStringFromCGRect(CGRectZero)]) {
            
            self.bottomTouchView.hidden = NO;
            [self resetBottomTouchFrame];
        }
        
    } else if(scrollView.contentOffset.y < 0){
        
        if (self.topTouchView.hidden == YES  && self.previousDataList) {

            self.topTouchView.hidden = NO;
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    [self.chatBottomView.inputTextField resignFirstResponder];

}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    CGFloat height = scrollView.contentSize.height - scrollView.frame.size.height;
    if (height<0) {
        height = 0;
    }
    
    if (scrollView.contentOffset.y > height + 100) {
        
        NSNumber *isNodata = @0;
        if (self.dataListOne.count == 0) {
            isNodata = @1;
        } else if (self.dataListOne.count == 1) {
            SessonContentMessage *message = self.dataListOne[0];
            if ([message.sys_code isEqualToString:@"9999"] || [message.sys_code isEqualToString:@"1005"]) {

                isNodata = @1;
            }
        }
        
        
        if ([isNodata isEqual: @1]) {
            
            NSDictionary *dicrection = [NSDictionary dictionaryWithObjectsAndKeys:@"KDiretionUp",@"KDirection",isNodata,@"isNodata", nil];
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:@"KGoNextNotification" object:nil userInfo:dicrection];
            
        } else {
            
            CGFloat y_point = self.bottomTouchView.frame.origin.y;
            
            self.tableView.bounces = NO;
            [UIView animateWithDuration:0.5 animations:^{
                
                self.tableView.contentInset = UIEdgeInsetsMake(-y_point, 0, 0, 0);
                
            } completion:^(BOOL finished) {
                
                NSDictionary *dicrection = [NSDictionary dictionaryWithObjectsAndKeys:@"KDiretionUp",@"KDirection",isNodata,@"isNodata", nil];
                NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
                [center postNotificationName:@"KGoNextNotification" object:nil userInfo:dicrection];
                
                self.tableView.bounces = YES;
                self.bottomTouchView.hidden = YES;
                self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
                if (self.subjectPluginTableView.superview) {
                    [self.subjectPluginTableView removeFromSuperview];
                }
                if (self.sessionPluginTableView.superview) {
                    [self.sessionPluginTableView removeFromSuperview];
                }
            }];
        }
        
    } else if(scrollView.contentOffset.y < -80){
        
        if (self.topTouchView.hidden == NO) {
            

            CGFloat y_point = self.topTouchView.frame.size.height;
            
            self.tableView.bounces = NO;
            

            [UIView animateWithDuration:0.5 animations:^{
                
                CGFloat newHeight = self.tableView.contentSize.height + KTableViewHeight;
                self.tableView.frame = CGRectMake(0, 20 + KScrollViewTop, kScreenWidth, newHeight);

                self.tableView.contentInset = UIEdgeInsetsMake(y_point, 0, 0, 0);
                
            } completion:^(BOOL finished) {
                
                NSDictionary *dicrection = [NSDictionary dictionaryWithObjectsAndKeys:@"KDiretionDown",@"KDirection", nil];
                NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
                [center postNotificationName:@"KGoNextNotification" object:nil userInfo:dicrection];
                
                self.tableView.bounces = YES;
                self.topTouchView.hidden = YES;
                self.tableView.frame = CGRectMake(0, 20 + KScrollViewTop, kScreenWidth, KTableViewHeight);
                self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
                
                if (self.subjectPluginTableView.superview) {
                    [self.subjectPluginTableView removeFromSuperview];
                }
                if (self.sessionPluginTableView.superview) {
                    [self.sessionPluginTableView removeFromSuperview];
                }
            }];
        }
    }
}

#pragma mark - IFlySpeechSynthesizerDelegate

- (void) onCompleted:(IFlySpeechError *) error{

    if (error.errorCode == 0) {
        
        NSLog(@"语音合成成功!");
        
    } else {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:kCurrentKeyWindow animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = error.errorDesc;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
    }
}

//合成开始
- (void) onSpeakBegin{

}

//合成缓冲进度
- (void) onBufferProgress:(int) progress message:(NSString *)msg{

}

//合成播放进度
- (void) onSpeakProgress:(int) progress{

}

#pragma mark - TouchTableViewDelegate

- (void)tableView:(UITableView *)tableView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
{
    [self.chatBottomView.inputTextField resignFirstResponder];
}

- (void)tableView:(UITableView *)tableView touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.chatBottomView.inputTextField resignFirstResponder];
}

- (void)tableView:(UITableView *)tableView touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
}

- (void)tableView:(UITableView *)tableView touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.chatBottomView.inputTextField resignFirstResponder];
}

@end
